package cn.itcast.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.service.base.SubAreaServcie;

//四个注解
@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class SubAreaAction extends BaseAction<SubArea>{
	//注入 service层
	@Autowired
	private SubAreaServcie subAreaServcie;
	//添加分区 功能
	@Action(value="sub_area_save" ,results={@Result(name="success",location="./pages/base/sub_area.html" ,type="redirect")})
	public String save(){
		subAreaServcie.save((SubArea)model);
		return SUCCESS;
	}
	//修改分区
	//删除分区
	//查询分区
	@Action(value="sub_area_pageQuery",results=@Result(name="success",type="json"))
	public String pageQuery(){
		Pageable pageable = new PageRequest(page-1, rows);
		Page<SubArea> pageData = subAreaServcie.pageQuery( null,pageable);
		//将结果压入值栈
		this.pushPageDataToValueStack(pageData);
		return SUCCESS;
	}
	//属性驱动,构建上传文件需要的属性   
	private File file;
	private String fileFileName;
	public void setFile(File file) {
		this.file = file;
	}
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}


	//导入分区
	@Action(value = "sub_area_batchImport")
	public String batchImport() {
		//创建一个集合 存放所有的 SubArea对象
		List<SubArea> list = new ArrayList<SubArea>();
		String msg =null;
		try {
			// 1.加载Excel文件对象
			Workbook workbook = null;
			if (fileFileName.endsWith(".xls")) {
				workbook = new HSSFWorkbook(new FileInputStream(file));
			} else if (fileFileName.endsWith(".xlsx")) {
				workbook = new XSSFWorkbook(file);
			}
			//2.获得sheet对象  即:获得了每行数据的一个集合/数组     可以根据索引/名称
			Sheet sheet = workbook.getSheetAt(0);
			//3.遍历 获取每一行数据
			for (Row row : sheet) {
				//一行数据对应一个 subArea对象  而且需要跳过第一行 和空白行
				if(row.getRowNum()==0){
					continue;//跳过第一行
				}
				if(row.getCell(0)==null||
						StringUtils.isBlank(row.getCell(0).getStringCellValue())){
					continue;
				}
				//将每行数据  封装到 SubArea 对象中
				SubArea subArea = new SubArea();
				FixedArea fixedArea = new FixedArea();
				Area area = new Area();
				subArea.setId(row.getCell(0).getStringCellValue());//分区编号-----id
				System.out.println(row.getCell(0).getStringCellValue());//_---------------------
				
				fixedArea.setId(row.getCell(1).getStringCellValue()); //定区编码-----定区id
				subArea.setFixedArea(fixedArea);
				
				area.setId(row.getCell(2).getStringCellValue());
				subArea.setArea(area);
				
				subArea.setKeyWords(row.getCell(3).getStringCellValue());//关键字
				System.out.println(row.getCell(4).getStringCellValue());//========================
				subArea.setStartNum(row.getCell(4).getStringCellValue());//起始号
				System.out.println(row.getCell(5).getStringCellValue());//--------------------------------
				subArea.setEndNum(row.getCell(5).getStringCellValue());//结束号
				System.out.println(row.getCell(6).getStringCellValue().toCharArray()[0]);//------------------------
				subArea.setSingle(row.getCell(6).getStringCellValue().toCharArray()[0]);//单双号
				subArea.setAssistKeyWords(row.getCell(7).getStringCellValue());//辅助信息   位置信息
				//将数据存储到 集合中
				list.add(subArea);
			}
			//调用service层  保存数据
			subAreaServcie.saveBatch(list);
			msg="上传成功!!!";
		} catch (Exception e) {
			msg="上传失败!!!";
			e.printStackTrace();
		}
		//中文乱码处理
		ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
		try {
			ServletActionContext.getResponse().getWriter().write(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return NONE;
	}
	
	// 导出分区
	@Action(value="sub_area_batchExport")
	public String batchExport(){
		try{
		
		//1.查询所有 分区 对象  获得一个 List集合
		List<SubArea> subAreas = subAreaServcie.findAll();
		//2.通过 POI将 集合数据 写到 excel中
		//2.1创建一个 Workbook对象
		HSSFWorkbook workbook = new HSSFWorkbook();
		//计算一共 多少个sheet ,每页 5000条
		int totalNum = (int) Math.ceil(subAreas.size()*1.0/5000);
		for (int i = 0; i < totalNum ; i++) { //写一个sheet
			//2.2 创建一个sheet 对象
			HSSFSheet sheet = workbook.createSheet("分区数据"+i);
			//2.3创建表头行
			HSSFRow firstRow = sheet.createRow(0);
			//2.4创建 表头行 的单元 格
			firstRow.createCell(0).setCellValue("分区编号");
			firstRow.createCell(1).setCellValue("定区编码");
			firstRow.createCell(2).setCellValue("区域编码");
			firstRow.createCell(3).setCellValue("关键字");
			firstRow.createCell(4).setCellValue("起始号");
			firstRow.createCell(5).setCellValue("结束号");
			firstRow.createCell(6).setCellValue("单双号");
			firstRow.createCell(7).setCellValue("位置信息(辅助信息)");
			
			//2.5添加数据  遍历list集合  ,设置每一sheet 数据的开始 与结束标识
			int start  = i*5000; //集合开始遍历的角标
			int end = (i+1)*5000;//集合结束遍历的角标
			if(end >= subAreas.size()){
				end =subAreas.size();
			}
			for (int j = start; j < end; j++) {
				//创建一个  row对象
				HSSFRow row = sheet.createRow(sheet.getLastRowNum()+1);
				SubArea subArea = subAreas.get(j);
				row.createCell(0).setCellValue(subArea.getId());//分区 id
				row.createCell(1).setCellValue(subArea.getFixedArea().getId());//定区编码
				row.createCell(2).setCellValue(subArea.getArea().getId());//区域编码
				row.createCell(3).setCellValue(subArea.getKeyWords());//关键字
				row.createCell(4).setCellValue(subArea.getStartNum());//起始号
				row.createCell(5).setCellValue(subArea.getEndNum());//结束号
				row.createCell(6).setCellValue(subArea.getSingle());//单双号
				row.createCell(7).setCellValue(subArea.getAssistKeyWords());//辅助信息   位置信息
			}
		}
		//3.文件下载
		/*
		 * 两个头：
		 * 	content-Type:
		 *  content-disposition:指定客户端打开文件的方式
		 *  	* 默认：inline，在浏览器中打开
		 *  	* 下载： attachment;filename = xxx
		 * 一个流：
		 * 	response输出流：response.getOutputStream()
		 */
		//4.将workbook写入流
		HttpServletResponse response = ServletActionContext.getResponse();
		String filename ="fqsj.xls";
		String mimeType = ServletActionContext.getServletContext().getMimeType(filename);
		//设置文件类型------------------------------------------------------------------
		response.setContentType(mimeType);
		//content-disposition :指定客户端打开文件的方式
		response.setHeader("content-disposition", "attachment;filename="+filename);
		
		workbook.write(response.getOutputStream());
		//即通过response的输出流将workbook写到出去
		}catch(Exception e){
			e.printStackTrace();
		}
		return NONE;
	}
	

}
